/**
 * 打地鼠游戏控制脚本
 * Author   :jxyi
 * Date     :2017-3-20
 */

cc.Class({
    extends: cc.Component,

    properties: {
        
    },

    // use this for initialization
    onLoad: function () {
        this.holes = [];
        this.score = 0;

        // 获取分数的标签
        this.scoreLabel = cc.find('score', this.node).getComponent(cc.Label);
        this.scoreLabel.string = 'score: ' + this.score;

        // 预处理地洞（按钮）
        for (var i = 1; i < 10; ++i){
            var btn = cc.find('hole' + i, this.node);

            // 动态添加组件
            var btnLogic = btn.addComponent('btnLogic');
            this.holes.push(btnLogic);

            // 添加自定义事件的监听
            btn.on('addScore', this.onAddScore, this);
            btn.on('desScore', this.onDesScore, this);

            // 设置按钮点击时无变化
            btn.getComponent(cc.Button).transition = cc.Button.Transition.NONE;
        }

        this.schedule(this.dispatchShrewmouse, 0.3);
    },

    onAddScore: function(event) {
        ++this.score;
        this.scoreLabel.string = 'score: ' + this.score;
        event.stopPropagation();
    },
    
    onDesScore: function(event) {
        --this.score;
        this.scoreLabel.string = 'score: ' + this.score;
        event.stopPropagation();
    },

    dispatchShrewmouse: function() {
        var chance = Math.floor(Math.random() * 3);
        if (chance < 1){
            var index = Math.floor(Math.random() * this.holes.length);
            this.holes[index].addShrewmouse();
        }
    }
});
